const db = uniCloud.database();
const collection = db.collection("merchant-auth");

module.exports = {
  // 插入商户认证数据
  async updateByCustomer(merchantData) {
    try {
      await collection.add({
        ...merchantData,
        auth_status: "pending",
      });

      return {
        code: 0,
        message: "数据插入成功",
      };
    } catch (e) {
      return {
        code: 500,
        message: `数据库操作失败: ${e.message}`,
      };
    }
  },

  // 管理员修改商户认证数据
  // 在 updateByManager 中添加状态验证
  async updateByManager(formDataId, merchantData) {
    try {
      if (!merchantData.auth_status) {
        throw new Error("审核状态不能为空");
      }
      // 验证状态值
      const validStatus = ["pending", "approved", "rejected"];
      if (!validStatus.includes(merchantData.auth_status)) {
        throw new Error("无效的审核状态");
      }
      const result = await collection.doc(formDataId).update({
        ...merchantData,
        audit_time: Date.now(),
        auth_status: merchantData.auth_status,
      });

      return {
        code: 0,
        message: "数据修改成功",
      };
    } catch (e) {
      return {
        code: 500,
        message: `数据库操作失败: ${e.message}`,
      };
    }
  },
};
